package com.yanx.system.web.query;

import com.querydsl.core.BooleanBuilder;
import com.yanx.common.command.Executor;
import com.yanx.common.core.command.PageQryCommand;
import com.yanx.system.base.domain.entity.QSysMenu;
import com.yanx.system.base.domain.entity.rel.QSysRoleMenu;
import com.yanx.system.base.model.vo.SysRoleVo;
import com.yanx.system.base.query.SysRoleByIdQry;
import lombok.AllArgsConstructor;

import java.util.List;

/**
 * 根据角色ID查询菜单权限ID集合
 *
 * @author: gotanks
 * @create: 2023-2-9
 */
@AllArgsConstructor
public class SysMenuIdListByRoleIdQry extends PageQryCommand<List<Long>> {

    private Long roleId;

    @Override
    public List<Long> execute(Executor executor) {
        QSysMenu sysMenu = QSysMenu.sysMenu;
        QSysRoleMenu sysRoleMenu = QSysRoleMenu.sysRoleMenu;

        SysRoleVo sysRoleVo = executor.execute(new SysRoleByIdQry(roleId));

        //查询条件
        BooleanBuilder condition = new BooleanBuilder();
        condition.and(sysMenu.deleted.eq(false));
        if (sysRoleVo.isMenuCheckStrictly()) {
            condition.and(sysMenu.id.notIn(
                    queryFactory.select(sysMenu.parentId)
                            .from(sysMenu)
                            .innerJoin(sysRoleMenu).on(sysRoleMenu.menuId.eq(sysMenu.id), sysRoleMenu.roleId.eq(roleId))
            ));
        }
        List<Long> idList = queryFactory.select(sysMenu.id)
                .from(sysMenu)
                .leftJoin(sysRoleMenu).on(sysRoleMenu.menuId.eq(sysMenu.id))
                .where(condition, sysRoleMenu.roleId.eq(roleId))
                .orderBy(sysMenu.parentId.asc(), sysMenu.orderNum.asc())
                .fetch();
        return idList;
    }
}